package app.dev.ems.service.impl;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import app.dev.ems.data.element.FieldType;
import app.dev.ems.data.model.impl.Field;
import app.dev.ems.data.model.impl.ProfileSettings;
import app.dev.ems.dto.AvailableComponent;
import app.dev.ems.service.IComponentHandlerService;

public class ComponentHandlerServiceImpl implements IComponentHandlerService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public String getTextFieldLabel(Field textField, ProfileSettings profileSettings) {
		java.lang.reflect.Field[] fields = profileSettings.getClass().getDeclaredFields();
		for (java.lang.reflect.Field field : fields) {
			if (field.getName().equals(textField.getName())) {
				try {						
					field.setAccessible(true);									
					return (String) field.get(profileSettings);
				} catch (Exception exception) {
					logger.info("Error occurred during access to the textfield: " + exception.getMessage());
					return null;
				}
			}
		}
		return null;
	}
	
	public void clearTextFieldValue(Field textField, ProfileSettings profileSettings) {
		java.lang.reflect.Field[] fields = profileSettings.getClass().getDeclaredFields();
		for (java.lang.reflect.Field field : fields) {
			if (field.getName().equals(textField.getName())) {					
				try {
					field.setAccessible(true);
					field.set(profileSettings, "");
					break;
				} catch (Exception exception) {
					logger.info("Error occurred during access to the textfield: " + exception.getMessage());						
				}
			}
		}
	}
	
	public List<AvailableComponent> getAvailableComponents(ProfileSettings profileSettings) {
		List<AvailableComponent> availableComponents = new ArrayList<AvailableComponent>(0);
		EnumMap<FieldType, AvailableComponent> componentMap = new EnumMap<FieldType, AvailableComponent>(FieldType.class);
		for (Field field : profileSettings.getFields()) {
			if(field.isInUse()) {
				continue;
			}
			
			AvailableComponent availableComponent = componentMap.get(field.getFieldType());
			if(availableComponent == null) {
				availableComponent = new AvailableComponent(field.getDisplayName(), 1, field.getFieldType());
				availableComponents.add(availableComponent);
				componentMap.put(field.getFieldType(), availableComponent);
			} else {
				availableComponent.increaseAvailability();
			}
		}
		return availableComponents;
	}
}
